package com.zhuhjay.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Nullable;

/**
 * @author ZhuHJay
 * @date 2023/1/13 12:06
 */
@Slf4j
// @ControllerAdvice(basePackages = "com.zhuhjay.controller")
public class GlobalResponseBodyHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info(
                "\nResponseBodyAdvice supports:\n" +
                        "\tMethodParameter -> {}\n" +
                        "\tClass -> {}",
                returnType, converterType
        );
        return true;
    }

    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info(
                "\nResponseBodyAdvice beforeBodyWrite:\n" +
                        "\tObject -> {}\n" +
                        "\tMethodParameter -> {}\n" +
                        "\tMediaType -> {}\n" +
                        "\tClass -> {}",
                body, returnType, selectedContentType, selectedConverterType
        );
        return body;
    }
}
